<?php

	if (!isset($sAPP) || !is_string($sAPP) || !isset($aSUITE) || !is_array($aSUITE) || !isset($aSUITE[$sAPP])) {

	   	/**
		 * Intercetto la situazione in cui viene eseguito direttamente questo script (ovvero quando
		 * questo script non e' incluso in $sapp/index.php
		 *
		 */

		header('Location: ../index.php?sMsg=app-not-defined');
		die();
	}  
	
	fnGetValueFromGET(array('sTable','sAction','sField','sAlias','sLabel','iTableShow','iSelectShow','iRadiobShow','iExcelShow','iSetting'));

	$sScript = fnCurrentScript();
	$sSCRIPT_ROOT_PATH = (fnIsScriptInRoot() ? '.' : '..'); // Variabile utilizzata in template.php
	
	fnEvaluateTablesAccessLvl($aTABLE_SECURITY_CHECK, false);

	if(!isset($sTable) || !isset($aTABLE[$sTable])) {
		$sTable = fnTableDefault($sTABLE_DEFAULT, $aTABLE);
	}
	
	fnTableConst($sTable);
	
	$iAccessLvl = (!is_null(fnGetAccessLvl('table', $sTable)) && fnGetAccessLvl('table', $sTable) == -1 ? fnGetAccessLvl('table', $sTable) : max(fnGetAccessLvl('app'),fnGetAccessLvl('table', $sTable)));
	
	/**
	 * SPIEGAZIONE: se l'accesso a $sTable è negato, lascio come valore di $iAccessLvl -1 (ovvero:
	 * "accesso negato"). Altrimenti tengo valido il valore più grande tra $iAccessLvl per $sTable
	 * (se è stato definito) e $iAccessLvl per sAPP (che sicuramente è stato definito).
	 *
	 */
	 
	$bSEARCH_FORM_SHOW = false;
	$sJQueryValidateRule = '';

	$sMessageFlash = fnMessageFlash();

	if (is_allowed('sysop', $iAccessLvl)) {

		switch ($sAction) {
			
			case 'new':
			
				//
				// CODICE HTML PAGINA "AGGIUNGI IMPOSTAZIONE"
				//
			
				$sLEFT_NAV_IMG = "preferences.png";
				$sHeaderTitle = $sTableTitle = "$sAPP_NAME &raquo; Impostazioni &raquo; Aggiungi";
				
				$sHeadContent = "
					<script type='text/javascript' src='../include/jquery.validate.min.js'></script>
					<script type='text/javascript' src='../include/messages_it.js'></script>
					<script type='text/javascript' src='../include/methods_it.js'></script>
					<script type='text/javascript'>
						
						$().ready(function() {
							
							$(\"select[name='sTable']\").val('$sTable');
							
							$('button').button();
							
							$('#settings-new').validate({
								rules: {
									sField: { required: true }
								}
							});
											
						});
					</script>";
				
				$html .= "<a href='./settings.php?sTable=$sTable'>&laquo; Ritorna a: $sAPP_NAME &raquo; Impostazioni &raquo; $sTableName</a>";

				$html .= "<form id='settings-new' method='get' action='./settings.php'>";

				$html .= "<input type='hidden' name='sAction' value='add'>";
			
					$html .= "<table><tbody>";

					$html .= "<tr>
								<th>sTable</th>
								<td>
									<select id='sTable' name='sTable'>";
					
					$html .= fnTablesNamesOptions();
					
					$html .= "		</select>";

					$html .= "	</td></tr>";
								
					$html .= "<tr>
								<th>sField</th>
								<td>
									<input type='text' id='sField' name='sField'>
								</td></tr>";
								
					$html .= "<tr>
								<th>sAlias</th>
								<td>
									<input type='text' id='sAlias' name='sAlias'>
								</td></tr>";
								
					$html .= "<tr>
								<th>sLabel</th>
								<td>
									<input type='text' id='sLabel' name='sLabel'>
								</td></tr>";
					
					$html .= "<tr>
								<th>Table</th>
								<td>
									<input type='checkbox' value='1' id='iTableShow' name='iTableShow'>
								</td></tr>";
								
					$html .= "<tr>
								<th>Select</th>
								<td>
									<input type='checkbox' value='1' id='iSelectShow' name='iSelectShow'>
								</td></tr>";
								
					$html .= "<tr>
								<th>Radiob</th>
								<td>
									<input type='checkbox' value='1' id='iRadiobShow' name='iRadiobShow'>
								</td></tr>";
								
					$html .= "<tr>
								<th>Excel</th>
								<td>
									<input type='checkbox' value='1' id='iExcelShow' name='iExcelShow'>
								</td></tr>";
								
					$html .= "<tr>
								<th>&nbsp;</th>
								<td>
								<button id='submit' type='submit'>Salva</button>
								</td></tr>";
								
					$html .= "</tbody></table>";

					$html .= "</form>";
													
				break;
				
			case 'add':
			
				//
				// CODICE MYSQL: INSERT INTO `settings` ...
				//
			
				$sQuery = "	INSERT INTO `settings`
								(`id`, `sField`, `sAlias`, `sLabel`, `iTableShow`, `iSelectShow`, `iRadiobShow`, `iExcelShow`, `iOrdering`, `iSortable`, `sWidth`, `sApp`, `sTable`)
							VALUES
								(NULL, '$sField', '$sAlias', '$sLabel', '".(isset($iTableShow) ? $iTableShow : 0)."', '".(isset($iSelectShow) ? $iSelectShow : 0)."', '".(isset($iRadiobShow) ? $iRadiobShow : 0)."', '".(isset($iExcelShow) ? $iExcelShow : 0)."', '0', '0', '', '$sAPP', '$sTable')";
				$rResult = custom_mysql_query($sQuery);	
				
				$iSettingNew = mysql_insert_id();
				
				fnUpdateLog('NEW SETTING ['.$sTable.']', 0, '','I');	
				header("Location: ./settings.php?sTable=$sTable&iSettingNew=$iSettingNew");
				die();
				
				break;
				
			default:

				//
				// CODICE HTML PAGINA "VISUALIZZA IMPOSTAZIONI"
				//
				
				$sLEFT_NAV_IMG = "preferences.png";
				$sTableTitle = "$sAPP_NAME &raquo; Impostazioni &raquo; $sTableName <span style='font-size: 0.7em'>($sTableDescription)</span>";
				$sHeaderTitle = strip_tags($sTableTitle);
				$sNewItem = "<a href='./settings.php?sTable=$sTable&sAction=new'>Aggiungi &raquo;</a>";
				
				$sHeadContent = "
				
					<script type='text/javascript' src='../include/dataTables/media/js/jquery.dataTables.js'></script>
					<script type='text/javascript' src='../include/jquery.jeditable.mini.js'></script>
					
					<link type='text/css' href='../include/dataTables/media/css/demo_table.css' rel='stylesheet' />
					
			
					<script type='text/javascript' charset='utf-8'>
			
						var oTable;
						var oClicked;
						
						function fnRemoveSelected(oObj){
							$(oObj.fnSettings().aoData).each(function() {
								$(this.nTr).removeClass('row_selected');
							});
						}
									
						/* Get the rows which are currently selected */
						function fnGetSelected(oTableLocal) {
							var aReturn = new Array();
							var aTrs = oTableLocal.fnGetNodes();
							for (var i=0; i<aTrs.length; i++) {
								if ($(aTrs[i]).hasClass('row_selected')) {
									aReturn.push(aTrs[i]);
								}
							}
							return aReturn;
						}
			
						function fnTrash(iSetting, sTable) {
							$.getJSON('../include/settings.toggle.php', { 'sAPP': '$sAPP', 'sTable': sTable, 'iSetting': iSetting, 'sAction': 'trash' }, function (json) {
								if (json[0].sAction == 'trash' && json[0].sError == '') {
									var anSelected = fnGetSelected(oTable);
									oTable.fnDeleteRow(anSelected[0]);
								} else {
									alert ('Errore: ' + json[0].sError);
								}
							} );
						};
						
						function fnToggle2 (oObj) {
							src = oObj.attr('src') ,
							onCheck = /\_on\.png$/ ,
							offCheck = /\_off\.png$/ ;
							
							$.getJSON('../include/settings.toggle.php', {'sAPP': '$sAPP', 'sTable': '$sTable', 'iSetting': oObj.parents('tr:first').attr('iSetting'), 'sAction': 'toggle', 'sField': oObj.attr('sField'), 'sValue': (src.match(onCheck) ? 0 : 1) }, function (json) {
								if (json[0].sAction=='toggle' && json[0].sError=='') { 
									if(src.match(onCheck)) {
										oObj.attr('src', src.replace(onCheck, '_off.png'));
									} else if (src.match(offCheck)) {
										oObj.attr('src', src.replace(offCheck, '_on.png'));
									}
								} else { 
									alert ('Errore: ' + json[0].sError);
								} 		
							})
							
						}
				
						$(document).ready(function() {
						
							setTimeout(function(){
								$('.ui-message-flash').fadeOut();
							}, 1800);							
							
							/* Init DataTables */
							oTable = $('#settings').dataTable({
								'sDom': \"<'dt_filter'f>rt<'dt_info'ip><'dt_length'l>\",
								'oLanguage': { 'sUrl': '../include/dataTables/it_IT.txt' },		
								'bAutoWidth': false,
								'aaSorting': [[ 7, 'asc' ]],
								'iDisplayLength': 30,
								'aoColumnDefs': [ { 'sWidth': '20px', 'bSortable': false, 'aTargets': [ 3, 4, 5, 6, 8 ] },
												  { 'bSortable': false, 'aTargets': [ 10 ] }]
							});

							$(\"select[name='sTable']\").val('$sTable');

							$('#settings-form').change(function() {
								if ($('#settings-form #sTable').val() != '') {
									this.submit();
								}
							});


							$('.ui-toggable').click(function() {
								fnToggle2($(this));
							});	

							
							/* Apply the jEditable handlers to the table */
							$('.editable', oTable.fnGetNodes()).editable( '../include/settings.jeditable.php', {
								cancel : 'Annulla',
								submit : 'Salva',
								tooltip : 'Clicca per modificare',
								placeholder : '&nbsp;',
								cssclass : 'jeditable',
								name : 'sValue',
								'callback': function(sValue, y) {
									var aPos = oTable.fnGetPosition(this);
									oTable.fnUpdate(sValue, aPos[0], aPos[1]);
								},
								'submitdata': function(value, settings) {
									return {
										'sAPP': '$sAPP',
										'sTable': '$sTable',
										'sField': this.getAttribute('sField'),
										'iSetting': this.parentNode.getAttribute('iSetting'),
										'column': oTable.fnGetPosition(this)[2]
									};
								}
							});
							
							$('.settings-trash').click(function() {
								$(oTable.fnSettings().aoData).each(function() {
									$(this.nTr).removeClass('row_selected');
								});
								oClicked = $(this);
								oClicked.parent().parent().addClass('row_selected');
								$('#settings-trash-dialog').dialog('open');
								return false;
							});
							
							$('#settings-trash-dialog').dialog({
								autoOpen: false,
								resizable: false,
								modal: true,
								buttons: {
									'Elimina': function() {
										fnTrash(oClicked.attr('iSetting'), oClicked.attr('sTable'));
										$(this).dialog('close');
									},
									Annulla: function() {
										fnRemoveSelected(oTable);
										$(this).dialog('close');
									}
								}
							});
					
						});
						
					</script> ";
				
				$sQuery = fnQueryGetSettings($sAPP, $sTable);
				$aData = fnGetDataFromQuery($sQuery, 'fnQueryGetSettings()');
				
				$html .= "<div>&nbsp;</div>";
				
				$html .= "<table cellpadding='0' cellspacing='5'><tr><td>";
				
				$html .= "<form id='settings-form' action='settings.php'>";
				$html .= "	<select id='sTable' name='sTable'>";

				$html .= fnTablesNamesOptions();
				
				$html .= "	</select>";
				$html .= "</form>";
				
				$html .= "</td><td><a href='./index.php?sTable=$sTable'>&raquo; Vai alla tabella $sTableName</a></td></tr></table>";
					
				
				$html .= "<table class='display' id='settings' cellspacing='0' cellpadding='0'>";
				$html .= "	<thead>";
				$html .= "		<tr>";
				
				$html .= "			<th>sField</th>";
				$html .= "			<th>sAlias</th>";
				$html .= "			<th>sLabel</th>";
				$html .= "			<th>Table</th>";
				$html .= "			<th>Select</th>";
				$html .= "			<th>RadioB</th>";
				$html .= "			<th>Excel</th>";
				$html .= "			<th>iOrdering</th>";
				$html .= "			<th>iSortable</th>";
				$html .= "			<th>sWidth</th>";
				$html .= "			<th>sTable</th>";
				$html .= "			<th>&nbsp;</th>";
				$html .= "		</tr>";
				$html .= "	</thead>";
				$html .= "	<tbody>";
						
				if (!empty($aData)) {
					
					foreach ($aData as $aRow) {

						$html .= "<tr iSetting='".$aRow['id']."'>";
					
						$html .= "	<td class='editable' sField='sField'>".$aRow['sField']."</td>";
						$html .= "	<td class='editable' sField='sAlias'>".$aRow['sAlias']."</td>";
						$html .= "	<td class='editable' sField='sLabel'>".$aRow['sLabel']."</td>";
						
						$html .= "	<td class='center'><img class='ui-toggable' sField='iTableShow' src='../themes/common/images/wcheck_".($aRow['iTableShow']==1 ? "on" : "off").".png'></td>";
						$html .= "	<td class='center'><img class='ui-toggable' sField='iSelectShow' src='../themes/common/images/wcheck_".($aRow['iSelectShow']==1 ? "on" : "off").".png'></td>";
						$html .= "	<td class='center'><img class='ui-toggable' sField='iRadiobShow' src='../themes/common/images/wcheck_".($aRow['iRadiobShow']==1 ? "on" : "off").".png'></td>";
						$html .= "	<td class='center'><img class='ui-toggable' sField='iExcelShow' src='../themes/common/images/wcheck_".($aRow['iExcelShow']==1 ? "on" : "off").".png'></td>";
						
						$html .= "	<td class='editable' sField='iOrdering'>".$aRow['iOrdering']."</td>";
						
						$html .= "	<td class='center'><img class='ui-toggable' sField='iSortable' src='../themes/common/images/wcheck_".($aRow['iSortable']==1 ? "on" : "off").".png'></td>";
						
						$html .= "	<td class='editable' sField='sWidth'>".$aRow['sWidth']."</td>";
						
						$html .= "	<td class='editable' sField='sTable'>".$aRow['sTable']."</td>";						
						
						$html .= "	<td><img iSetting='".$aRow['id']."' sTable='".$aRow['sTable']."'class='settings-trash' src='../themes/common/images/icn_trash.gif'></td>";
			
						
						$html .= "</tr>";
						
					}
				}
				
				$html .= "	</tbody>";
				$html .= "</table>";

				$html .= "
					<div id='settings-trash-dialog' title='Elimina'>
						<p>Sei sicuro di voler eliminare la riga selezionata?</p>
						<p>Questa operazione non potrà essere annullata.</p>
				</div>";	

				break;		

		}

	} else {
		fnUpdateLog('LOW RIGHTS', 0, '','S');
		header("Location: ./index.php?sTable=$sTable&sMsg=low-rights");
		die();

	}		
	
	require_once('../themes/'.$sTHEME.'/template.php');
	die();
	
?><html><body bgcolor="#fff"></body></html>